package com.flexdms.i18n;

import java.io.IOException;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIOutput;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.Renderer;

public class BasicRenderer extends Renderer
{
	String basicAttrs[] = { "accesskey", "dir", "lang", "onblur", "onclick",
			"ondblclick", "onfocus", "onkeydown", "onkeypress", "onkeyup",
			"onmousedown", "onmousemove", "onmouseout", "onmouseover",
			"onmouseup", "role", "tabindex", "title" };

	public void writeGenericAttributes(UIComponent comp, ResponseWriter writer)
			throws IOException
	{
		Map<String, Object> attrMap = comp.getAttributes();
		for (String key : basicAttrs)
		{
			Object value = attrMap.get(key);
			if (value != null)
			{
				writer.writeAttribute(key, value, key);
			}
		}
		for (Map.Entry<String, Object> entry : comp.getPassThroughAttributes()
				.entrySet())
		{
			Object value = entry.getValue();
			if (value == null)
			{
				// do not write it as null
				value = "";
			}
			writer.writeAttribute(entry.getKey(), value, null);
		}
	}

	public void writeStyleAttributes(UIComponent comp, ResponseWriter writer)
			throws IOException
	{
		Map<String, Object> attrMap = comp.getAttributes();
		String key = "style";
		Object value = attrMap.get(key);
		if (value != null)
		{
			writer.writeAttribute(key, value, key);
		}
		
	}

	public String getLocalizedText(UIComponent comp)
	{
		return LocalizationHelper.getLocalizedMessage((UIOutput) comp);
	}

	public boolean getRendersChildren()
	{
		return true;
	}

	protected UIComponent getForComponent(FacesContext context,
			String forComponent, UIComponent component)
	{

		if (null == forComponent || forComponent.length() == 0)
		{
			return null;
		}

		UIComponent result = null;
		UIComponent currentParent = component;

		while (currentParent != null)
		{
			result = currentParent.findComponent(forComponent);
			if (result != null)
			{
				break;
			}
			currentParent = currentParent.getParent();
		}
		if (result == null)
		{
			result = context.getViewRoot().findComponent(forComponent);
		}
		return result;
	}

	protected Iterator<FacesMessage> getMessageIter(FacesContext context,
			String forComponent, UIComponent component)
	{

		Iterator<FacesMessage> messageIter;
		if (null != forComponent)
		{
			if (forComponent.length() == 0)
			{
				messageIter = context.getMessages(null);
			} else
			{
				UIComponent result = getForComponent(context, forComponent,
						component);
				if (result == null)
				{
					messageIter = Collections.EMPTY_LIST.iterator();
				} else
				{
					messageIter = context.getMessages(result
							.getClientId(context));
				}
			}
		} else
		{
			messageIter = context.getMessages();
		}
		return messageIter;

	}



}
